package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.CodeGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author kelvin
 * @date 2024-12-28
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否入住(by Id cardNo, status should be in (1,2,3,4))
        Elder elder = getElder(checkInApplyDto.getCheckInElderDto().getIdCardNo());
        //2.入住就终止业务
        if (elder != null) {
            throw new ServiceException("老人已经入住了");
        }
        //3.更新状态为已入住，防止并发
            //先查询 在更新
        updateBedStatus(checkInApplyDto.getCheckInConfigDto().getBedId());
        //4.新增或更新老人
        Elder elderInDB =insertOrUpdateElder(checkInApplyDto.getCheckInElderDto(),checkInApplyDto.getCheckInConfigDto().getBedId());
        //5.新增签约办理
        inserContract(checkInApplyDto,elderInDB);
        //6.新增入住办理
        CheckIn checkIn = insertCheckIn(checkInApplyDto,elderInDB);
        //7.新增入住配置
        insertCheckInConfig(checkIn.getId(),checkInApplyDto.getCheckInConfigDto());
    }

    private void insertCheckInConfig(Long id, CheckInConfigDto checkInConfigDto){
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(CheckInApplyDto checkInApplyDto,Elder elderInDB){
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(),CheckIn.class);
        checkIn.setIdCardNo(elderInDB.getIdCardNo());
        checkIn.setElderId(elderInDB.getId());
        checkIn.setBedNumber(elderInDB.getBedNumber());
        checkIn.setElderName(elderInDB.getName());
        checkIn.setStatus(0L); //已入住
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        save(checkIn);//mp的保存方法
        return checkIn;
    }

    private void inserContract(CheckInApplyDto checkInApplyDto,Elder elderInDB) {
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        //更新老人的信息
        contract.setElderName(elderInDB.getName());
        contract.setElderId(elderInDB.getId());
        //开始时间和结束时间
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //设置状态
        contract.setStatus(0);
        if(contract.getStartDate().isBefore(LocalDateTime.now())){
            contract.setStatus(1);
        }
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto,Long bedId) {
        //老人是否存在 id
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        //存在 更新
        Elder elderInDB = elderMapper.selectOne(queryWrapper);
        Bed bed = bedMapper.selectById(bedId);

        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        if (elderInDB == null) {
            elderMapper.insert(elder);
        }else {

            elder.setId(elderInDB.getId());
            //不存在 新增
            elderMapper.updateById(elder);
        }
        return elder;
    }

    private void updateBedStatus(Long bedId) {
        //构造查询条件
        LambdaUpdateWrapper<Bed> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Bed::getBedStatus,1)
                .eq(Bed::getId,bedId).eq(Bed::getBedStatus,0);
        //更新了几条记录
        int affectedRows = bedMapper.update(null,updateWrapper);
        if(affectedRows ==0){
            throw new ServiceException("请选择其他床位");
        }
    }

    private Elder getElder(String idCardNo) {
         //构建查询条件
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.in
                //1,2,3,4代表老人已入住
                (Elder::getStatus, List.of(1,2,3,4))
                .eq(Elder::getIdCardNo, idCardNo);
        return elderMapper.selectOne(elderLambdaQueryWrapper);
    }
}
